package de.keychain

class SecurityFilters {
	
	def securedControllers = ["configuration","serviceModel", "password", "app", "login"]
	LoginService loginService

	def filters = {
		httpAuth(controller:'*', action:'*') {
			before = {
				
				if(!session.user && securedControllers.contains(controllerName)){
					
					def authHeader = request.getHeader('Authorization')
					
					def loginResult = false
					
					if (authHeader) {
						def usernamePassword = new String(authHeader.split(' ')[1].decodeBase64()).split(":")
						
						if(usernamePassword.size()==2){						
							loginResult = loginService.login(usernamePassword[0],usernamePassword[1])
						}
						
						response.setHeader('WWW-Authenticate', 'basic realm="KeyChain"')
					}
					
					if(!loginResult){				
						response.sendError(response.SC_UNAUTHORIZED)
					}
					
					return loginResult
				}
							
				return true
			}
		}
	}
}
